import React, { useState, useRef, useEffect } from 'react';
import { 
  StyleSheet, 
  View, 
  ScrollView, 
  TextInput, 
  TouchableOpacity, 
  KeyboardAvoidingView, 
  Platform,
  ActivityIndicator,
  SafeAreaView
} from 'react-native';
import OpenAI from "openai";
import { ChatCompletionMessageParam } from "openai/resources/chat/completions";

import { ThemedText } from '@/components/ThemedText';
import { FontAwesome } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
// 定义消息类型
interface Message {
  id: string;
  content: string;
  type: 'user' | 'ai';
  timestamp: Date;
}

// 定义 API 消息类型
interface ApiMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

export default function ChatScreen() {
  const API_KEY = 'sk-eefwdkcgfqpwdjyitvchrrwkxezqmafgnsixhhllpbpqfxnb'; // 替换为你的 API key

  const [messages, setMessages] = useState<Message[]>([]);
  const [inputText, setInputText] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const scrollViewRef = useRef<ScrollView>(null);

  // 保存所有对话历史
  const [chatHistory, setChatHistory] = useState<ApiMessage[]>([
    { role: "system" as const, content: "You are a helpful assistant." }
  ]);

  const [abortController, setAbortController] = useState<AbortController | null>(null);

  // 添加一个状态来存储当前正在流式输出的消息
  const [streamingMessage, setStreamingMessage] = useState<Message | null>(null);

  // 自动滚动到底部
  useEffect(() => {
    setTimeout(() => {
      scrollViewRef.current?.scrollToEnd({ animated: true });
    }, 100);
  }, [messages]);

  // 取消请求
  const handleCancel = () => {
    if (abortController) {
      abortController.abort();
      setIsLoading(false);
      setAbortController(null);
    }
  };

  // 发送消息
  const handleSend = async () => {
    if (!inputText.trim() || isLoading) return;

    // 创建新的 AbortController
    const controller = new AbortController();
    setAbortController(controller);

    // 创建用户消息
    const userMessage: Message = {
      id: Date.now().toString(),
      content: inputText.trim(),
      type: 'user',
      timestamp: new Date()
    };

    // 添加用户消息到列表
    setMessages(prev => [...prev, userMessage]);
    setInputText('');
    setIsLoading(true);

    try {
      // 更新对话历史
      const newChatHistory: ApiMessage[] = [
        ...chatHistory,
        { role: "user" as const, content: inputText.trim() }
      ];
      setChatHistory(newChatHistory);

      // 创建初始的流式消息
      const initialStreamMessage: Message = {
        id: (Date.now() + 1).toString(),
        content: '',
        type: 'ai',
        timestamp: new Date()
      };
      setStreamingMessage(initialStreamMessage);
      
      // 调用 API
      const options = {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Connection': 'keep-alive',
          'Cache-Control': 'no-cache'
        },
        body: JSON.stringify({
          model: "deepseek-ai/DeepSeek-V2.5",
          messages: newChatHistory,
          stream: true,
          max_tokens: 2000,
          temperature: 0.7,
          tools: []
        })
      };

      // 使用 XMLHttpRequest 处理流式响应
      const xhr = new XMLHttpRequest();
      xhr.open('POST', 'https://api.siliconflow.cn/v1/chat/completions', true);
      
      // 设置请求头
      Object.entries(options.headers).forEach(([key, value]) => {
        xhr.setRequestHeader(key, value as string);
      });

      // 处理错误
      xhr.onerror = () => {
        throw new Error('网络连接失败，请检查网络设置');
      };

      let accumulatedContent = '';
      let displayContent = '';
      let lastProcessedIndex = 0;
      let currentIndex = 0;
      let typingTimer: NodeJS.Timeout | null = null;

      const startTypewriterEffect = (text: string) => {
        if (typingTimer) {
          clearInterval(typingTimer);
        }
        
        currentIndex = displayContent.length;
        typingTimer = setInterval(() => {
          if (currentIndex < text.length) {
            displayContent = text.slice(0, currentIndex + 1);
            setStreamingMessage(prev => prev ? {
              ...prev,
              content: displayContent
            } : null);
            currentIndex++;
          } else {
            if (typingTimer) {
              clearInterval(typingTimer);
            }
          }
        }, 30); // 打字速度，可以调整
      };
      
      // 处理数据流
      xhr.onprogress = (event) => {
        try {
          const newData = xhr.responseText.slice(lastProcessedIndex);
          lastProcessedIndex = xhr.responseText.length;
          
          const lines = newData.split('\n');
          
          for (const line of lines) {
            if (line.trim() === '') continue;
            if (line === 'data: [DONE]') continue;
            if (!line.startsWith('data: ')) continue;

            try {
              const data = JSON.parse(line.slice(6));
              const content = data.choices?.[0]?.delta?.content || '';
              if (content) {
                accumulatedContent += content;
                startTypewriterEffect(accumulatedContent);
              }
            } catch (parseError) {
              continue;
            }
          }
        } catch (error) {
          console.warn('处理响应数据时出错:', error);
        }
      };

      // 处理完成
      xhr.onload = () => {
        if (typingTimer) {
          clearInterval(typingTimer);
        }

        if (xhr.status !== 200) {
          let errorMessage = '请求失败';
          try {
            const errorData = JSON.parse(xhr.responseText);
            errorMessage = errorData.error?.message || `服务器错误 (${xhr.status})`;
          } catch (e) {
            errorMessage = `服务器错误 (${xhr.status})`;
          }
          throw new Error(errorMessage);
        }

        if (!accumulatedContent.trim()) {
          throw new Error('未收到有效的响应数据');
        }

        // 确保显示完整的内容
        setStreamingMessage(prev => prev ? {
          ...prev,
          content: accumulatedContent
        } : null);

        // 流式输出完成后，将消息添加到消息列表
        setMessages(prev => [...prev, {
          ...initialStreamMessage,
          content: accumulatedContent
        }]);
        
        setChatHistory(prev => [...prev, { 
          role: "assistant" as const, 
          content: accumulatedContent 
        }]);

        setIsLoading(false);
        setStreamingMessage(null);
      };

      // 发送请求
      xhr.send(options.body);

      // 设置取消处理
      controller.signal.addEventListener('abort', () => {
        if (typingTimer) {
          clearInterval(typingTimer);
        }
        xhr.abort();
      });

    } catch (error: any) {
      if (error.name === 'AbortError') {
        setStreamingMessage(null);
        return;
      }
      
      console.error('API 调用错误:', error);
      const errorMessage: Message = {
        id: (Date.now() + 1).toString(),
        content: error.message.includes('Insufficient Balance') 
          ? '账户余额不足，请充值后再试。'
          : `抱歉，发生了错误：${error.message}`,
        type: 'ai',
        timestamp: new Date()
      };
      setMessages(prev => [...prev, errorMessage]);
    } finally {
      setIsLoading(false);
      setAbortController(null);
      setStreamingMessage(null);
    }
  };

  // 渲染单个消息
  const renderMessage = (message: Message) => {
    const isAI = message.type === 'ai';
    return (
      <View 
        key={message.id} 
        style={[
          styles.messageContainer,
          isAI ? styles.aiMessage : styles.userMessage
        ]}
      >
        <View style={styles.messageContent}>
          {isAI && (
            <View style={styles.avatar}>
              <LinearGradient
                colors={['#64B5F6', '#90CAF9']}
                style={styles.avatarGradient}
              >
                <FontAwesome name="android" size={16} color="#fff" />
              </LinearGradient>
            </View>
          )}
          <View 
            style={[
              styles.messageBubble,
              isAI ? styles.aiBubble : styles.userBubble
            ]}
          >
            <ThemedText style={[
              styles.messageText,
              isAI ? styles.aiText : styles.userText
            ]}>
              {message.content}
            </ThemedText>
          </View>
          {!isAI && (
            <View style={styles.avatar}>
              <LinearGradient
                colors={['#64B5F6', '#90CAF9']}
                style={styles.avatarGradient}
              >
                <FontAwesome name="user" size={16} color="#fff" />
              </LinearGradient>
            </View>
          )}
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.safeArea}>
      <KeyboardAvoidingView 
        style={styles.container}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
      >
        <View style={styles.header}>
          <ThemedText style={styles.headerTitle}>AI 助手</ThemedText>
        </View>

        <ScrollView 
          ref={scrollViewRef}
          style={styles.messagesContainer}
          contentContainerStyle={styles.messagesContent}
        >
          {messages.map(renderMessage)}
          {streamingMessage && renderMessage(streamingMessage)}
          {isLoading && !streamingMessage && (
            <View style={styles.loadingContainer}>
              <ActivityIndicator color="#FF9F45" />
              <ThemedText style={styles.loadingText}>AI 正在思考...</ThemedText>
            </View>
          )}
        </ScrollView>

        <View style={styles.inputContainer}>
          <TextInput
            style={styles.input}
            value={inputText}
            onChangeText={setInputText}
            placeholder="输入消息..."
            placeholderTextColor="#999"
            multiline
            maxLength={500}
            editable={!isLoading}
          />
          <TouchableOpacity 
            style={[
              styles.sendButton,
              isLoading ? styles.sendButtonActive : (!inputText.trim() && styles.sendButtonDisabled)
            ]} 
            onPress={isLoading ? handleCancel : handleSend}
            disabled={!inputText.trim() && !isLoading}
          >
            <LinearGradient
              colors={['#64B5F6', '#90CAF9']}
              style={styles.sendButtonGradient}
            >
              <FontAwesome 
                name={isLoading ? "stop" : "send"} 
                size={20} 
                color="#fff" 
              />
            </LinearGradient>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#fff',
    paddingTop: Platform.OS === 'android' ? 25 : 0,
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    backgroundColor: '#fff',
    paddingTop: Platform.OS === 'android' ? 8 : 16,
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#64B5F6',
  },
  messagesContainer: {
    flex: 1,
    backgroundColor: '#F8FBFD',
  },
  messagesContent: {
    padding: 16,
  },
  messageContainer: {
    marginBottom: 16,
  },
  messageContent: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    maxWidth: '80%',
  },
  aiMessage: {
    alignSelf: 'flex-start',
  },
  userMessage: {
    alignSelf: 'flex-end',
  },
  avatar: {
    width: 32,
    height: 32,
    borderRadius: 16,
    overflow: 'hidden',
    marginHorizontal: 8,
  },
  avatarGradient: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  messageBubble: {
    padding: 12,
    borderRadius: 16,
    maxWidth: '100%',
  },
  aiBubble: {
    backgroundColor: '#E3F2FD',
    borderWidth: 1,
    borderColor: '#BBDEFB',
  },
  userBubble: {
    backgroundColor: '#64B5F6',
  },
  messageText: {
    fontSize: 16,
    lineHeight: 22,
  },
  aiText: {
    color: '#333',
  },
  userText: {
    color: '#fff',
  },
  loadingContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 16,
    gap: 8,
  },
  loadingText: {
    color: '#64B5F6',
    fontSize: 14,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    padding: 16,
    paddingBottom: 20,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  input: {
    flex: 1,
    minHeight: 40,
    maxHeight: 100,
    backgroundColor: '#E3F2FD',
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingVertical: 8,
    fontSize: 16,
    color: '#333',
    marginRight: 12,
  },
  sendButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    overflow: 'hidden',
    justifyContent: 'center',
    alignItems: 'center',
  },
  sendButtonDisabled: {
    opacity: 0.5,
  },
  sendButtonActive: {
    opacity: 1,
  },
  sendButtonGradient: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#64B5F6',
    borderRadius: 20,
  },
}); 